package org.ssssssss.magicapi.ftp;

import cn.hutool.extra.ssh.JschUtil;
import java.lang.Class;
import java.lang.reflect.Field;

import com.jcraft.jsch.*;

public class SftpUtil {
	
	public static boolean read(String ip,int port,String name,String pwd, String code,
			String souFile,String desFile) {
		boolean rtn = false;
		try {		
			// 1、建立会话
			Session session = JschUtil.getSession(ip, port, name, pwd);
			// 2、获取sftp通道
			ChannelSftp channel = (ChannelSftp)session.openChannel("sftp");		
			// 3、连接通道
			channel.connect();

			// 使用反射修改server_version的默认值
			if("gbk".equals(code)) {
				Class cl = channel.getClass();//.class;
				Field f1= cl.getDeclaredField("server_version");
				f1.setAccessible(true);
				f1.set(channel, 2); 
				channel.setFilenameEncoding("gbk");			
			}
			if (channel.isConnected()) {
			    // 下载文件
			    channel.get(souFile, desFile);
			    rtn = true;
			} else {
			    // "连接SFTP服务器失败"
			}
			// 4、关闭通道连接
			JschUtil.close(channel);
			// 5、关闭session会话
			JschUtil.close(session);
		} catch (JSchException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchFieldException | SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		catch (SftpException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return rtn;
	}
}
